package com.ysucode.config;

import com.ysucode.controller.user.advice.CheckCodeFilter;
import com.ysucode.controller.user.advice.LoginFailureHandler;
import com.ysucode.controller.user.advice.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * SpringSecurity的配置类
 */
@Configuration
@EnableWebSecurity //添加security过滤器
@EnableGlobalMethodSecurity(prePostEnabled = true) //启用方法级别的权限认证
public class SecurityConfig {
    @Autowired
    private LoginSuccessHandler loginSuccessHandler; //登录成功的拦截器
    @Autowired
    private LoginFailureHandler loginFailureHandler; //登录失败的拦截器
    @Autowired
    private CheckCodeFilter checkCodeFilter; //校验验证码的拦截器

    //BCrypt加盐加密
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //配置安全认证服务，这里只需要声明UserDetailsService和BCryptPasswordEncoder两个全局Bean即可
    //配置过滤器链
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        //添加校验验证码的过滤器
        httpSecurity.addFilterBefore(checkCodeFilter, UsernamePasswordAuthenticationFilter.class);
        //释放静态资源、设置拦截规则、设置自定义页面、指定退出认证配置、csrf配置
        httpSecurity
                .authorizeRequests()
                .antMatchers("/index", "/registerServlet", "/pages/500.html",
                        "/css/**", "/imgs/**", "/js/**", "/plugins/**",
                        "/checkCodeServlet")
                .permitAll()
                .antMatchers("/**").hasAnyRole("COMMON") //这里默认加了ROLE_前缀
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/loginServlet")
                .successHandler(loginSuccessHandler)
                //.successForwardUrl("/WEB-INF/jsp/index.jsp")
                .failureHandler(loginFailureHandler)
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/WEB-INF/jsp/index.jsp")
                .invalidateHttpSession(true) //清空session
                .permitAll()
                .and()
                .csrf() //关闭csrf跨域攻击
                .disable();
        return httpSecurity.build();
    }

}
